﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
using System;

namespace IOP.AspNetCore.Extension.UploadServer
{
    /// <summary>
    /// 
    /// </summary>
    public static class UploadServerMiddlewareExtensions
    {
        /// <summary>
        /// 启用上传服务器
        /// </summary>
        /// <param name="app"></param>
        /// <param name="option"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseUploadServer(this IApplicationBuilder app, Action<UploadOption> option)
        {
            var _option = new UploadOption();
            option?.Invoke(_option);
            var fileServerOptions = new FileServerOptions();
            fileServerOptions.FileProvider = new PhysicalFileProvider(_option.PhysicPath);
            fileServerOptions.EnableDirectoryBrowsing = false;
            fileServerOptions.RequestPath = _option.FileRequestPath;
            var mime = new FileExtensionContentTypeProvider(_option.MIMEMapping);
            fileServerOptions.StaticFileOptions.ContentTypeProvider = mime;
            app.UseFileServer(fileServerOptions);
            app.UseMiddleware<UploadServerMiddleware>(_option);
            return app;
        }
    }
}
